package com.star.security.filter;

import com.star.security.authentication.AnonymousAuthenticationToken;
import com.star.security.authentication.Authentication;
import com.star.security.context.TokenContextHolder;
import com.star.security.context.TokenRepository;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 令牌上下文持有者过滤器
 *
 * @author yangzj
 */
public class TokenContextHolderFilter extends OncePerRequestFilter {

    private final TokenRepository tokenRepository;
    private final AnonymousAuthenticationRequest anonymousAuthenticationRequest;

    public TokenContextHolderFilter(TokenRepository tokenRepository, AnonymousAuthenticationRequest anonymousAuthenticationRequest) {
        this.tokenRepository = tokenRepository;
        this.anonymousAuthenticationRequest = anonymousAuthenticationRequest;
    }

    @SuppressWarnings("NullableProblems")
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        try {
            boolean matches = anonymousAuthenticationRequest.matches(request);
            Authentication authentication = matches ? AnonymousAuthenticationToken.authenticated() : this.tokenRepository.get(request);
            TokenContextHolder.setContext(authentication);
            filterChain.doFilter(request, response);
        } finally {
            TokenContextHolder.clearContext();
        }
    }
}
